package com.teacher.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teacher.common.CommonResult;
import com.teacher.common.JwtTokenUtil;
import com.teacher.mapper.CarpoolPostMapper;
import com.teacher.mapper.WechatUserMapper;
import com.teacher.pojo.dto.comment.CommentAddDto;
import com.teacher.pojo.dto.comment.CommentDto;
import com.teacher.pojo.dto.comment.CommentUpdateDto;
import com.teacher.pojo.dto.notice.NoticeAddDto;
import com.teacher.pojo.entity.CarpoolPost;
import com.teacher.pojo.entity.Comment;
import com.teacher.mapper.CommentMapper;
import com.teacher.pojo.entity.WechatUser;
import com.teacher.pojo.vo.comment.CommentVo;
import com.teacher.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiangzhuohang
 * @since 2024-03-14
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private WechatUserMapper wechatUserMapper;

    @Autowired
    private CarpoolPostMapper carpoolPostMapper;

    @Autowired
    private NoticeServiceImpl noticeService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private HttpServletRequest httpServletRequest;



    @Override
    public IPage<CommentVo> getCommentPageData(CommentDto pageVo) {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
//        System.out.println(userDetails.getUsername());
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);

        Page page = new Page(pageVo.getCurrentPage(), pageVo.getPageSize());
        IPage<CommentVo> commentPageData = commentMapper.getCommentPageData(page, pageVo);
        return commentPageData;
    }

    @Override
    public CommonResult addComment(CommentAddDto dto) {
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);

        CarpoolPost carpoolPost = carpoolPostMapper.selectById(dto.getCarpoolId());
        if (BeanUtil.isEmpty(carpoolPost)){
            return CommonResult.failed("未找到该拼车信息");
        }


        Comment comment = new Comment();
        BeanUtil.copyProperties(dto,comment);
        comment.setCommentatorOpenId(openid);
        int insert = commentMapper.insert(comment);
        if (insert<1) {
            return CommonResult.failed("新增失败");
        }


        //改变评价对象信誉分
        WechatUser wechatUser = wechatUserMapper.selectOne(new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, dto.getCommenteeOpenId()));
        Float oldScore = wechatUser.getCreditScore();
        Float changeScore = dto.getScore();
        Float newScore = (oldScore+changeScore)/2;

        wechatUser.setCreditScore(newScore);
        int i = wechatUserMapper.updateById(wechatUser);
        if (i<1){
            return CommonResult.failed("更新用户信誉分出错清联系管理员");
        }

        //
        String text = "好评";
        if (dto.getScore()<3){
            text="差评";
        }else if (3<=dto.getScore() && dto.getScore()<4){
            text="中评";
        }
        //通知表
        NoticeAddDto noticeAddDto = new NoticeAddDto();
        noticeAddDto.setType("1");
        noticeAddDto.setAcceptOpenId(dto.getCommenteeOpenId());
        noticeAddDto.setSendName("被评价通知");
        noticeAddDto.setSendOpenId(openid);
        noticeAddDto.setRelevanceId(dto.getCarpoolId());
        noticeAddDto.setContent("你收到了一条"+text);

        noticeService.addNotice(noticeAddDto);

        //异步调用微信小程序推送消息
        noticeService.sendCarpoolCommentMessage(dto.getCommenteeOpenId(),dto.getCarpoolId(),text,dto.getScore());


        return CommonResult.success("评价成功");
    }

    @Override
    public CommonResult deleteComment(List<Long> list) {
        int i = commentMapper.deleteBatchIds(list);
        if (i<1){
            return CommonResult.failed("删除失败");
        }
        return CommonResult.success("删除成功");
    }

    @Override
    public CommonResult updateComment(CommentUpdateDto updateDto) {
        Comment comment = new Comment();
        BeanUtil.copyProperties(updateDto,comment);
        comment.setStatus(1);

        int i = commentMapper.updateById(comment);
        if (i<1){
            return CommonResult.failed("更新失败");
        }
        //改变评价对象信誉分
        WechatUser wechatUser = wechatUserMapper.selectOne(new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, updateDto.getCommenteeOpenId()));
        Float oldScore = wechatUser.getCreditScore();
        Float changeScore = updateDto.getScore();
        Float newScore = (oldScore+changeScore)/2;

        wechatUser.setCreditScore(newScore);
        int insert = wechatUserMapper.updateById(wechatUser);
        if (insert<1){
            return CommonResult.failed("更新用户信誉分出错清联系管理员");
        }

        //
        String text = "好评";
        if (updateDto.getScore()<3){
            text="差评";
        }else if (3<=updateDto.getScore() && updateDto.getScore()<4){
            text="中评";
        }
        //通知表
        NoticeAddDto noticeAddDto = new NoticeAddDto();
        noticeAddDto.setType("3");
        noticeAddDto.setAcceptOpenId(updateDto.getCommenteeOpenId());
        noticeAddDto.setSendName("被评价通知");
        noticeAddDto.setSendOpenId(updateDto.getCommentatorOpenId());
        noticeAddDto.setRelevanceId(updateDto.getId());
        noticeAddDto.setContent("你收到了一条"+text);

        noticeService.addNotice(noticeAddDto);

        //异步调用微信小程序推送消息
        noticeService.sendCarpoolCommentMessage(updateDto.getCommenteeOpenId(),updateDto.getId(),text,updateDto.getScore());


        return CommonResult.success("更新成功");
    }

    @Override
    public Boolean createComment(WechatUser AUser, WechatUser BUser, Long carpoolId, LocalDateTime endTime) {


        Comment comment = new Comment();
        comment.setCommentatorName(AUser.getName());
        comment.setCommentatorOpenId(AUser.getOpenId());
        comment.setCarpoolId(carpoolId);
        comment.setEndTime(endTime);
        comment.setCommenteeName(BUser.getName());
        comment.setCommenteeOpenId(BUser.getOpenId());

        commentMapper.insert(comment);
        Comment comment2 = new Comment();
        comment2.setEndTime(endTime);
        comment2.setCarpoolId(carpoolId);
        comment2.setCommentatorName(BUser.getName());
        comment2.setCommentatorOpenId(BUser.getOpenId());
        comment.setCommenteeName(AUser.getName());
        comment2.setCommenteeOpenId(AUser.getOpenId());
        int insert = commentMapper.insert(comment2);
        if (insert < 1 ){
            return false;
        }
        return true;
    }


}
